<!-- 商品中心 - 商品列表  -->
<template>
  <doc-alert title="【商品】商品 SPU 与 SKU" url="https://doc.iocoder.cn/mall/product-spu-sku/" />
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="展示方式" prop="showType">
            <el-select v-model="queryParams.showType" clearable disabled>
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SHOW_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="商品品牌" prop="brandId">
            <el-select v-model="queryParams.brandId" clearable>
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="商品名称" prop="spuName">
            <el-input
              v-model="queryParams.spuName"
              clearable
              placeholder="请输入商品名称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="商品分类" prop="categoryId">
            <el-cascader
              v-model="queryParams.categoryId"
              :options="categoryList"
              :props="defaultProps"
              class="w-100%!"
              clearable
              filterable
              placeholder="请选择商品分类"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="6">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
            <el-button v-hasPermi="[createPermi]" plain type="primary" @click="openForm(undefined)">
              <Icon class="mr-5px" icon="ep:plus" />
              新增
            </el-button>
            <el-button
              v-hasPermi="[exportPermi]"
              :loading="exportLoading"
              plain
              type="success"
              @click="handleExport"
            >
              <Icon class="mr-5px" icon="ep:download" />
              导出
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-tabs v-model="queryParams.tabType" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="item in tabsData"
        :key="item.type"
        :label="item.name + '(' + item.count + ')'"
        :name="item.type"
      />
    </el-tabs>
    <el-table v-loading="loading" :data="list">
      <el-table-column type="expand">
        <template #default="{ row }">
          <el-form class="spu-table-expand" label-position="left">
            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="划线价:">
                      <span>{{ fenToYuan(row.marketPrice) }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="最低价:">
                      <span>{{ fenToYuan(row.lowPrice) }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="成本价:">
                      <span>{{ fenToYuan(row.costPrice) }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="排序:">
                      <span>{{ row.sort }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="上架销量:">
                      <span>{{ row.salesCount }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="线下销量:">
                      <span>{{ row.virtualSalesCount }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="浏览量:">
                      <span>{{ row.browseCount }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="收藏:">
                      <span>暂未上线</span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="商品分类:">
                      <el-tooltip
                        effect="dark"
                        :content="formatCategoryName(row.categoryId)"
                        placement="top"
                      >
                        <div>
                          {{ formatCategoryName(row.categoryId) }}
                        </div>
                      </el-tooltip>
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label="创建人:">
                      <span>{{ row.creator }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="创建时间:">
                      <span>{{ formatDate(row.createTime) }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="库存:">
                      <span>{{ row.stock }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="操作人:">
                      <span>{{ row.updater }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="操作时间:">
                      <span>{{ formatDate(row.updateTime) }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="ID" prop="spuId" :align="'center'" />
      <!-- <el-table-column label="品牌" :align="'center'" prop="brandName" /> -->
      <el-table-column label="商品信息" min-width="320">
        <template #default="{ row }">
          <div class="flex flex-items-center">
            <el-image
              fit="cover"
              :src="row.picUrl"
              class="flex-none w-50px h-50px rounded-4px"
              @click="imagePreview(row.picUrl)"
            />
            <div class="ml-4 overflow-hidden">
              <el-tooltip effect="dark" :content="row.spuName" placement="top">
                <div>
                  <!-- <el-tag v-if="row.brandName">{{ row.brandName }}</el-tag> -->
                  {{ row.spuName }}
                </div>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="零售价" min-width="160" prop="price">
        <template #default="{ row }">
          <div class="flex justify-center items-center">
            <!-- ¥ {{ fenToYuan(row.price) }} -->
            {{ row.priceRange }}
            <Icon
              icon="ep:edit-pen"
              v-if="true"
              class="cursor-pointer p-l-5px c-[var(--el-color-primary)]!"
              @click="openUpdatePriceTenant(row.spuId)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="销售渠道" min-width="160" prop="salesChannelName" />
      <el-table-column label="来源" align="center" min-width="70" prop="tenantType">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.TENANT_IDENTITY" :value="row.tenantType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="销售状态" min-width="80">
        <template #default="{ row }">
          <template v-if="row.status >= 0">
            <el-switch
              v-model="row.status"
              :disabled="!row.operable"
              :active-value="1"
              :inactive-value="0"
              active-text="上架"
              inactive-text="下架"
              inline-prompt
              @change="handleStatusChange(row)"
            />
          </template>
          <template v-else>
            <el-tag type="info">回收站</el-tag>
          </template>
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="操作" min-width="200">
        <template #default="{ row }">
          <el-button link type="primary" @click="openDetail(row.spuId)"> 详情 </el-button>
          <template v-if="row.operable">
            <el-button v-hasPermi="[updatePermi]" link type="primary" @click="openForm(row.spuId)">
              修改
            </el-button>
            <template v-if="queryParams.tabType === 4">
              <el-button
                v-hasPermi="[deletePermi]"
                link
                type="danger"
                @click="handleDelete(row.spuId)"
              >
                删除
              </el-button>
              <el-button
                v-hasPermi="[updatePermi]"
                link
                type="primary"
                @click="handleStatus02Change(row, ProductSpuStatusEnum.DISABLE.status)"
              >
                恢复
              </el-button>
            </template>
            <template v-else>
              <el-button
                v-hasPermi="[updatePermi]"
                link
                type="danger"
                @click="handleStatus02Change(row, ProductSpuStatusEnum.RECYCLE.status)"
              >
                回收
              </el-button>
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 门店SKU改价 -->
    <UpdatePriceTenantDialog ref="UpdatePriceTenantDialogRef" @success="handleQuery()" />
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script lang="ts" setup>
import { ElTable, TabsPaneContext } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { defaultProps, handleTree } from '@/utils/tree'
import { ProductSpuStatusEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import * as ProductBrandApi from '@/api/mall/product/brand'
import * as TenantApi from '@/api/system/tenant'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { useProductUtils } from '@/views/mall/product/hooks/useProduct'
import UpdatePriceTenantDialog from '../components/UpdatePriceTenantDialog.vue'
const { formatCategoryNameByCategoryList } = useProductUtils()
defineOptions({ name: 'ProductSpu' })
import { defaultShortcuts } from '@/utils/formatTime'
/**时间范围限制 */
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转

const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据

// tabs 数据
const tabsData = ref([
  {
    name: '出售中',
    type: 0,
    count: 0
  },
  {
    name: '仓库中',
    type: 1,
    count: 0
  },
  {
    name: '已售罄',
    type: 2,
    count: 0
  },
  {
    name: '警戒库存',
    type: 3,
    count: 0
  },
  {
    name: '回收站',
    type: 4,
    count: 0
  }
])

const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  tabType: 0,
  spuName: '',
  categoryStoreId: undefined,
  categoryId: undefined,
  createTime: undefined,
  showType: 0, //商品展示方式 0 SPU 1 SKU
  tenantType: [], // 商品来源
  brandId: [], //商品品牌
  salesOnlineChannel: [], //线上渠道
  salesChannel: [] as EmptyArrayType, //销售渠道
  salesOffineChannel: [] as EmptyArrayType, //销售门店
  salesAtlChannel: [] as EmptyArrayType, //销售商城
  spuType: '1'
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref
const createPermi = ref('product:spu:create') //新增权限
const updatePermi = ref('product:spu:update') //修改权限
const deletePermi = ref('product:spu:delete') //删除权限
const exportPermi = ref('product:spu:export') //导出权限

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductSpuApi.getSpuPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName as number
  getList()
}

/** 获得每个 Tab 的数量 */
const getTabsCount = async () => {
  const res = await ProductSpuApi.getTabsCount({ spuType: queryParams.value.spuType })
  for (let objName in res) {
    tabsData.value[Number(objName)].count = res[objName]
  }
}

/** 添加到仓库 / 回收站的状态 */
const handleStatus02Change = async (row: any, newStatus: number) => {
  try {
    // 二次确认
    const text = newStatus === ProductSpuStatusEnum.RECYCLE.status ? '加入到回收站' : '恢复到仓库'
    await message.confirm(`确认要"${row.spuName}"${text}吗？`)
    // 发起修改
    await ProductSpuApi.updateStatus({ spuId: row.spuId, status: newStatus })
    message.success(text + '成功')
    // 刷新 tabs 数据
    await getTabsCount()
    // 刷新列表
    await getList()
  } catch {}
}

/** 更新上架/下架状态 */
const handleStatusChange = async (row: any) => {
  try {
    // 二次确认
    const text = row.status ? '上架' : '下架'
    await message.confirm(`确认要${text}"${row.spuName}"吗？`)
    // 发起修改
    await ProductSpuApi.updateStatus({ spuId: row.spuId, status: row.status })
    message.success(text + '成功')
    // 刷新 tabs 数据
    await getTabsCount()
    // 刷新列表
    await getList()
  } catch {
    // 异常时，需要重置回之前的值
    row.status =
      row.status === ProductSpuStatusEnum.DISABLE.status
        ? ProductSpuStatusEnum.ENABLE.status
        : ProductSpuStatusEnum.DISABLE.status
  }
}

/** 删除按钮操作 */
const handleDelete = async (spuId: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductSpuApi.deleteSpu(spuId)
    message.success(t('common.delSuccess'))
    // 刷新tabs数据
    await getTabsCount()
    // 刷新列表
    await getList()
  } catch {}
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 新增或修改 */
const openForm = (spuId?: number) => {
  // 修改
  if (typeof spuId === 'number') {
    push({ name: 'ProductSpuEdit', params: { spuId } })
    return
  }
  // 新增
  push({ name: 'ProductSpuAdd' })
}

/** 查看商品详情 */
const openDetail = (spuId: number) => {
  push({ name: 'ProductSpuDetail', params: { spuId } })
}
/**  商户改价 */
const UpdatePriceTenantDialogRef = ref()
const openUpdatePriceTenant = (spuId: number) => {
  UpdatePriceTenantDialogRef.value.open(spuId)
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductSpuApi.exportSpu(queryParams)
    download.excel(data, '商品列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/** 获取分类的节点的完整结构 */
const categoryList = ref() // 商城分类树
const formatCategoryName = (categoryId: number[]) => {
  return formatCategoryNameByCategoryList(categoryId, categoryList.value)
}

/** 激活时 */
onActivated(() => {
  getList()
})
/** 初始化 **/
const brandList = ref<any[]>([]) // 商品品牌列表
const storeList = ref<any[]>([]) // 门店列表
const shopList = ref<any[]>([]) //商城列表
onMounted(async () => {
  await getTabsCount()
  await getList()
  // 获得商品分类树
  const categoryListData = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(categoryListData, 'id', 'parentId')
  // 获取商品品牌列表
  brandList.value = await ProductBrandApi.getSimpleBrandList()
  // 获取门店列表
  const storeData = await TenantApi.getTenantPage({ tenantType: 4 })
  storeList.value = storeData.list
  // 获取商城列表

  const shopData = await TenantApi.getTenantPage({ tenantType: 5 })
  shopList.value = shopData.list
})
</script>
<style lang="scss" scoped>
.spu-table-expand {
  padding-left: 42px;

  :deep(.el-form-item__label) {
    width: 82px;
    font-weight: bold;
    color: #99a9bf;
  }
}
</style>
